/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.core.persistence;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import com.inspur.edp.lcm.metadata.common.MetadataSerializer;
import com.inspur.edp.lcm.metadata.common.Utils;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class MetadataRepository {
    private FileServiceImp fileService = new FileServiceImp();
    MetadataSerializer metadataSerializer = new MetadataSerializer();

    public GspMetadata load(String absolutePath) {
        String fileString = fileService.fileRead(absolutePath);
        GspMetadata metadata = metadataSerializer.deserialize(fileString, GspMetadata.class);
        metadata.setRelativePath(absolutePath.substring(0, Utils.handlePath(absolutePath).lastIndexOf('/')));
        return metadata;
    }

    public GspMetadata getMetadataWithoutContent(String path) {
        String fileStr = fileService.fileRead(path);
        if (fileStr == null || fileStr.isEmpty()) {
            return null;
        }
        ObjectMapper mapper = Utils.getMapper();
        JsonNode metadataObj = null;
        try {
            metadataObj = mapper.readTree(fileStr);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        }
        GspMetadata metadata = metadataSerializer.buildMetadataBaseInfo(metadataObj);
        metadata.setRelativePath(path.substring(0, Utils.handlePath(path).lastIndexOf('/')));
        return metadata;
    }

    public void getMetadatasUnderDir(List<String> mdPathList, String dirPath) {
        List<File> dirs = fileService.getDirectorys(dirPath);
        if (dirs.size() > 0) {
            for (int i = 0; i < dirs.size(); i++) {
                String dirName = fileService.getFileName(Utils.handlePath(dirs.get(i).getPath()));
                String temPath = dirPath + "/" + dirName;
                if (!dirName.equalsIgnoreCase(".git") && !dirName.equalsIgnoreCase(".vs") && !dirName.equalsIgnoreCase("bin") && !dirName.toLowerCase().equals("publish") && !dirName.toLowerCase().equals("obj") && !dirName.toLowerCase().equals("src") && !dirName.toLowerCase().equals("java")) {
                    getMetadatasUnderDir(mdPathList, temPath);
                }
            }
        }
        List<File> paths = fileService.getAllFiles(dirPath);
        if (paths.size() > 0) {
            for (File path : paths) {
                mdPathList.add(Utils.handlePath(path.getPath()));
            }
        }
    }

    public void create(GspMetadata metadata, String path) {
        // 序列化元数据
        String metadataStr = metadataSerializer.serialize(metadata);
        String folderPath = new File(path).getParent();
        if (!fileService.isDirectoryExist(folderPath)) {
            fileService.createDirectory(folderPath);
        }
        fileService.createFile(path);
        fileService.fileUpdate(path, metadataStr, false);
    }

    public void save(GspMetadata metadata, String path) {
        // 序列化元数据
        String metadataStr = metadataSerializer.serialize(metadata);
        fileService.fileUpdate(path, metadataStr, false);
    }

    public void delete(String path) {
        try {
            fileService.fileDelete(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void rename(String oldName, String newName) {
        try {
            fileService.fileRename(oldName, newName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
